package com.kehutong.admin.security;

import java.util.Collections;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.coraframework.authz.AuthenticationInfo;
import org.coraframework.authz.AuthzRealm;
import org.coraframework.authz.exception.AuthenticationException;
import org.coraframework.authz.exception.NotPermissionException;
import org.coraframework.authz.exception.UnknownAccountException;
import org.coraframework.authz.util.CookieUtils;
import org.coraframework.authz.util.ThreadLocalServlet;
import org.coraframework.inject.Inject;
import org.coraframework.inject.Singleton;
import org.coraframework.orm.jdbc.JdbcSession;

import com.kehutong.admin.entity.User;
import com.kehutong.admin.util.CacheUtil;
import com.kehutong.admin.util.UserUtils;

/**
 * 系统安全认证实现类
 * 
 * @author liuzhen (liuxing521a@kuwan123.com)
 * @createTime 2018年4月21日下午2:26:33
 */
@Singleton
public class SystemAuthorizingRealm extends AuthzRealm {

	@Inject
	private CacheUtil cacheUtil;
	@Inject
	private JdbcSession jdbcSession;

	@Override
	protected Set<String> doGetAuthorizationRoles() {
//		Set<String> rule = new HashSet<>();
//
//		List<Role> rules = UserUtils.getRoleList(false);
//        assert rules != null;
//        rules.forEach(ru->rule.add(ru.getId()));

		return Collections.emptySet();
	}

	@Override
	protected Set<String> doGetAuthorizationPermissions() {
		try {
			return UserUtils.getPermissions(false);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationInfo authInfo) throws AuthenticationException {
		// 如果登录失败超过3次需要验证码
		if (UserUtils.isNeedValidCode(authInfo.getUserName())) {
			HttpServletRequest req = ThreadLocalServlet.current().getReq();
			String cookieValue = CookieUtils.getCookieValue(req);
			String validCode = cacheUtil.get(cookieValue + "_" + UserUtils.LOGIN);
			String verifyCode = authInfo.getSubject();
			if (verifyCode == null || !verifyCode.toUpperCase().equals(validCode)) {
				throw new NotPermissionException("验证码错误.");
			}

			cacheUtil.remove(cookieValue + "_" + UserUtils.LOGIN);
		}

		User user = jdbcSession.findOne(User.class)
				.eq("login_name", authInfo.getUserName())
				.exe();
		if (user == null || user.isDeleted()) {
			throw new UnknownAccountException("用户不存在");
		}

		return new AuthenticationInfo(user.getLogin_name(), user.getPassword(), user.getId());
	}

}
